
import re,jwt

from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from django.http import JsonResponse
from rest_framework import status

from users.utils import MyJwt
from users.models import UserModel,PermissionModel,PermissionRoleModel

class MyMiddleware(MiddlewareMixin):

    def process_request(self, request):
        path = request.path_info
        method = request.method.lower()  # GET = get
        print(path,method)

        if re.findall("login|image_code|register", path, re.I):
            return None

        token = request.headers.get("token", None)
        if not token:
            return JsonResponse({'code':status.HTTP_400_BAD_REQUEST,'msg':'token不存在'})
        myjwt = MyJwt()
        try:
            user = myjwt.decode(token)
        except Exception as e:
            return JsonResponse({'code': status.HTTP_400_BAD_REQUEST, 'msg': f'token不合法{e}'})
        try:
            users = UserModel.objects.filter(id=user['id']).first()
        except Exception as e:
            return JsonResponse({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'该用户不存在{e}'})


        user_queryset = UserModel.objects.filter(is_delete=False).all()
        permission_queryset = PermissionModel.objects.filter(is_delete=False).all()
        permission_role_queryset = PermissionRoleModel.objects.filter(is_delete=False).all()

        user = user_queryset.filter(id=users.id).first()
        if not user:
            return JsonResponse({'code':status.HTTP_400_BAD_REQUEST,'msg':'该用户不存在'})

        permission_role = permission_role_queryset.filter(role_id=user.role_id).all()

        permission_list = []
        for i in permission_role:
            permission = permission_queryset.filter(id=i.permission_id).values('permission_url')
            for j in permission:
                permission_list.append(j.get('permission_url'))
        for i in permission_list:
            per_method = i.split()[0]
            per_path = i.split()[1]
            if re.findall(per_path, path, re.I) and method == per_method:
                return None
        return JsonResponse({'code': status.HTTP_400_BAD_REQUEST, 'msg': '无权限访问！'}, status=status.HTTP_200_OK)
